<template>
  <div class="dishes-inventory-container">
    <h1>菜品库</h1>
    <!-- 筛选部分 -->
    <div class="filter-section">
      <el-input v-model="filter.dishName" placeholder="请输入菜品名称" clearable></el-input>
      <el-select v-model="filter.categoryName" placeholder="请选择菜品类别">
        <el-option v-for="category in dishCategories" :key="category.id" :label="category.name" :value="category.name"></el-option>
      </el-select>
      <el-select v-model="filter.storeId" placeholder="请选择门店">
        <el-option v-for="store in stores" :key="store.id" :label="store.name" :value="store.id"></el-option>
      </el-select>
      <el-button @click="queryDishes">查询</el-button>
    </div>
    <!-- 数据列表部分 -->
    <div class="data-list-section">
      <el-button @click="exportToExcel">导出Excel</el-button>
      <el-table :data="dishes" stripe>
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="dishName" label="名称"></el-table-column>
        <el-table-column prop="dishUnit" label="菜品单位"></el-table-column>
        <el-table-column prop="categoryName" label="分类"></el-table-column>
        <el-table-column prop="storeName" label="所属门店"></el-table-column>
        <el-table-column prop="stockQuantity" label="库存"></el-table-column>
        <el-table-column prop="checkTime" label="盘点时间"></el-table-column>
        <el-table-column prop="stockBottomLine" label="库存过底线"></el-table-column>
        <el-table-column prop="warningQuantity" label="库存超出线"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="viewAdjustmentRecord(scope.row.id)">调整记录</el-button>
            <el-button @click="editDish(scope.row.id)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3, 6, 9]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 调整记录弹窗 -->
    <el-dialog v-model="adjustmentRecordDialogVisible" title="调整记录" custom-class="adjustment-record-dialog">
      <el-table :data="adjustmentRecords" stripe>
        <el-table-column prop="time" label="时间"></el-table-column>
        <el-table-column prop="operator" label="操作人"></el-table-column>
        <el-table-column prop="operation" label="操作"></el-table-column>
        <el-table-column prop="previousStock" label="修改前库存"></el-table-column>
        <el-table-column prop="stockChange" label="库存变动"></el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3, 6, 9]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        >
        </el-pagination>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adjustmentRecordDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改菜品弹窗 -->
    <el-dialog v-model="editDishDialogVisible" title="修改菜品" custom-class="edit-dish-dialog">
      <el-form :model="editDishForm" label-width="120px">
        <el-form-item label="菜品名称">
          <el-input v-model="editDishForm.dishName" disabled></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model.number="editDishForm.stockQuantity" ></el-input>
        </el-form-item>
        <el-form-item label="库存过低预警数">
          <el-input v-model.number="editDishForm.stockBottomLine"></el-input>
        </el-form-item>
        <el-form-item label="库存超出预警数">
          <el-input v-model.number="editDishForm.warningQuantity"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDishDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEditDish">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 筛选条件，与 DishQueryDTO 对应
const filter = ref({
  dishName: '',
  categoryName: '',
  storeId: null,
  currentPage: 1,
  pageSize: 3
});

// 菜品类别
const dishCategories = ref([]);
// 门店列表
const stores = ref([]);
// 菜品数据，与 DishVO 对应
const dishes = ref([]);
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(10);
// 总条目数
const totalItems = ref(0);

// 调整记录弹窗相关，与 DishAdjustmentRecordVO 对应
const adjustmentRecordDialogVisible = ref(false);
const adjustmentRecords = ref([]);

// 修改菜品弹窗相关
const editDishDialogVisible = ref(false);
const editDishForm = ref({
  id: null,
  dishName: '',
  stockQuantity: 0,
  stockBottomLine: 0,
  warningQuantity: 0
});

// 查询菜品
const queryDishes = () => {
  filter.value.currentPage = currentPage.value;
  filter.value.pageSize = pageSize.value;
  axios.post(`/dish/query/${currentPage.value}/${pageSize.value}`, filter.value)
      .then(response => {
        dishes.value = response.data.records;
        totalItems.value = response.data.total;
      })
      .catch(error => {
        ElMessage.error('查询菜品失败，请稍后重试');
        console.error('查询菜品失败:', error);
      });
};

// 导出 Excel
const exportToExcel = () => {
  // 这里后续添加导出 Excel 的代码
  console.log('导出 Excel');
};

// 查看调整记录
const viewAdjustmentRecord = (id) => {
  adjustmentRecordDialogVisible.value = true;
  axios.post('/dish/adjustmentRecord', { id })
      .then(response => {
        adjustmentRecords.value = response.data;
      })
      .catch(error => {
        ElMessage.error('查看调整记录失败，请稍后重试');
        console.error('查看调整记录失败:', error);
      });
};

// 修改菜品
const editDish = (id) => {
  const dish = dishes.value.find(item => item.id === id);
  if (dish) {
    editDishForm.value = {
      id: dish.id,
      dishName: dish.dishName,
      stockQuantity: dish.stockQuantity,
      stockBottomLine: dish.stockBottomLine,
      warningQuantity: dish.warningQuantity
    };
    editDishDialogVisible.value = true;
  }
  console.log('修改菜品，ID：', id);
};

// 修改菜品方法
const saveEditDish = () => {
  // 假设的用户 ID，登录功能未实现，先传假数据
  const operatorId = 1;

  const dto = {
    dishId: editDishForm.value.id,
    stockQuantity: editDishForm.value.stockQuantity,
    intType: editDishForm.value.stockBottomLine,
    warningQuantity: editDishForm.value.warningQuantity,
    operatorId: operatorId
  };

  axios.post('/dishStock/update', dto)
      .then(response => {
        if (response.status === 200) {
          ElMessage.success('菜品库存更新成功');
          editDishDialogVisible.value = false;
          queryDishes(); // 更新列表数据
        } else {
          ElMessage.error('菜品库存更新失败：' + response.data);
        }
      })
      .catch(error => {
        ElMessage.error('菜品库存更新失败，请稍后重试');
        console.error('菜品库存更新失败:', error);
      });
};

// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  queryDishes();
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  queryDishes();
};

// 获取菜品类别
const getDishCategories = () => {
  axios.get('/dish/categories')
      .then(response => {
        dishCategories.value = response.data;
      })
      .catch(error => {
        ElMessage.error('获取菜品类别失败，请稍后重试');
        console.error('获取菜品类别失败:', error);
      });
};

// 获取门店列表
const getStores = () => {
  axios.get('/dish/stores')
      .then(response => {
        stores.value = response.data;
      })
      .catch(error => {
        ElMessage.error('获取门店列表失败，请稍后重试');
        console.error('获取门店列表失败:', error);
      });
};

// 组件挂载后初始化查询
onMounted(() => {
  getDishCategories();
  getStores();
  queryDishes();
});
</script>

<style scoped>
.dishes-inventory-container {
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.data-list-section button {
  margin-bottom: 10px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 调整记录弹窗样式 */
.adjustment-record-dialog .el-dialog__header {
  background-color: #f0f9eb;
  border-bottom: 1px solid #e9f3e3;
}

.adjustment-record-dialog .el-dialog__body {
  padding: 20px;
}

.adjustment-record-dialog .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #e9f3e3;
  text-align: right;
}

/* 修改菜品弹窗样式 */
.edit-dish-dialog .el-dialog__header {
  background-color: #f0f9eb;
  border-bottom: 1px solid #e9f3e3;
}

.edit-dish-dialog .el-dialog__body {
  padding: 20px;
}

.edit-dish-dialog .el-form-item {
  margin-bottom: 15px;
}

.edit-dish-dialog .el-input {
  border-radius: 4px;
}

.edit-dish-dialog .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #e9f3e3;
  text-align: right;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
}

.el-button--primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button--primary:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}
</style>